var xhttp = null;
var div_content = null;
var div_status = null;
var div_shadow = null;

function ajax_get(url)
{
    xhttp.open("GET", url);
    xhttp.send();
}

function create_ajax() {
    xhttp = new XMLHttpRequest();

    //中止事件
    xhttp.onabort = ajax_abort;
    //错误事件
    xhttp.onerror = ajax_error;
    //请求成功完成事件
    xhttp.onload = ajax_load;
    //不管成功失败，只要完成就触发
    xhttp.onloadend = ajax_loadend;
    //请求开始时触发
    xhttp.onloadstart = ajax_loadstart;
    //进度提示事件
    xhttp.onprogress = ajax_progress;
    //超时事件
    xhttp.ontimeout = ajax_timeout;
    //请求过程状态改变事件
    xhttp.onreadystatechange = ajax_readstatechange;
        /*
         * 0       创建XMLHttpRequest对象状态
         * 1       调用open方法的状态
         * 2       已收到服务器响应头
         * 3       已收到服务器响应正文
         * 4       响应完成或失败
         */
}

function ajax_abort(e)
{
    div_status.innerHTML += "中止事件<br />";
}

function ajax_loadend(e)
{
    div_shadow.hidden = true;
    div_status.innerHTML += "请求完成，不管成功与否<br />";
}

function ajax_loadstart(e)
{
    div_shadow.hidden = false;
    div_status.innerHTML += "请求开始<br />";
}

function ajax_load(e)
{
    div_status.innerHTML += "请求成功完成<br />";
}

function ajax_error(e)
{
    div_status.innerHTML += "请求错误<br />";
}

function ajax_progress(e)
{
    div_shadow.innerHTML += ".";
    div_status.innerHTML += "进度: " + e.loaded + "/" + e.total + "<br />";
}

function ajax_timeout(e)
{
    div_status.innerHTML += "请求超时<br />";
}

function ajax_readstatechange(e)
{
    var data = "请求失败, 请重试!";

    div_status.innerHTML += "readyState: " + xhttp.readyState + "<br />";

    if (xhttp.readyState == 4 && xhttp.status == 200) {
        data = xhttp.responseText;
    }
    div_content.innerHTML = data;
}

function init()
{
    create_ajax();

    div_content = document.querySelector(".content");
    div_status = document.querySelector(".status");
    div_shadow = document.querySelector(".shadow");

    div_shadow.hidden = true;

    var btn = document.querySelector(".get");
    btn.addEventListener("click", function(){
        ajax_get("weather.php?name=" + document.querySelector(".input").value);
        // 请求静态页面会直接将页面内容发送回来
        // ajax_get("index.html");
    });

    var capcha = document.querySelector(".capcha");
    capcha.addEventListener("click", function(){
        capcha.src = "capcha.php?v="+Math.random();
    });

}

init();

